var accessToken = "139436992894387|65471b8b3fdc60240f6b3a9e14284c1f";
var roomId;
var gameTitle;

function createWebSocketConnection(){
	ws = new WebSocket("ws://localhost:8080/playground/WebSocketServlet/select-game");
	ws.onopen = function(event) {
		console.log("connection opened");
		var msg = {action: "registerPlayerToSocket", playerId: $.cookie("playerId"), playerKey: $.cookie("playerKey")};
		ws.send(JSON.stringify(msg));
		console.log("message sent: " + JSON.stringify(msg));
	};
	
	ws.onmessage = function(event) {
		console.log("message received");
		console.log("json::: " + event.data);
		var data = jQuery.parseJSON(event.data);
		//console.log("object::: " + data);
		if (data.success){
			switch(data.action){
				case "registerPlayerToSocket":
					console.log("registration succeeded " + data.loggedPlayer.facebookId + " " + data.loggedPlayer.status);
					writeFacebookData(data.loggedPlayer.facebookId);
					break;
				case "waitForPlayersConfirmation":
					roomId = data.roomId;
					askIfPlayerWantsToJoinTheGame();
					break;
				case "roomIsReady":
					startGame(data.application);
			}
		} else{
			console.log("'" + data.action + "' failed.");
		}
		
	};
		
	ws.onclose = function(event) {
		console.log("connection closed");
	};
	
	ws.onerror = function(event) {
		console.data(event.data);
	}
}

// Display functions

function writeFacebookData(facebookId){
	var query = facebookId + "?fields=name,picture";
	var jsonUrl = "https://graph.facebook.com/" + query + "&access_token=" + accessToken;
	$.getJSON(jsonUrl, function(data){
		$("#facebook_username").html(data.name);
		$("#facebook_picture").html("<img src=\"" + data.picture.data.url + "\" alt=\"profile picture\" width=\"25\" height=\"25\" />");
	});
}

function alertEnteredQueue(){
	$("#info_bar").attr("class", "info_bar_success");
	$("#info_bar").html("You have entered the queue to \"" + gameTitle + "\". Please wait.");
	$("#info_bar").show();
}

function askIfPlayerWantsToJoinTheGame(){
	$("#info_bar").attr("class", "info_bar_success");
	$("#info_bar").html("The game \"" + gameTitle + "\" is ready to be played, click here to join it.");
	$("#info_bar").addClass("clickable");
	$("#info_bar").bind("click", confirmGame);
}

function alertWaitingForOtherPlayers(){
	$("#info_bar").unbind();
	$("#info_bar").attr("class", "info_bar_success");
	$("#info_bar").html("Waiting for other players to join the game.");
}

function startGame(application){
	console.log("Game is starting in: /WebSockets/" + application);
	ws.close();
	window.location.replace(simplifyString(application) + ".html?roomId=" + roomId);
}

function simplifyString(string){
	return string.toLowerCase();
}

// Messages functions

function enterQueue(gameId){
	gameTitle = $($("#gameLink\\:" + gameId + " h3")[0]).html();
	var msg = {action: "enterQueue", gameTitleId: gameId};
	ws.send(JSON.stringify(msg));
	console.log("message sent: " + JSON.stringify(msg));
	alertEnteredQueue();
}

function confirmGame(){
	var msg = {action: "joinGame"};
	ws.send(JSON.stringify(msg));
	console.log("message sent: " + JSON.stringify(msg));
	alertWaitingForOtherPlayers();
}

// Test game functions

function linkGames(){
	var games = $("div[id^='gameLink']");
	for (var i = 0; i < games.length; i++){
		$(games[i]).bind("click", function(){
			enterQueue($(this).attr("id").split(":")[1]);
		});
	}
}